package dmsxl.zhanyuduilie;

import java.util.Arrays;
import java.util.Stack;

/**
 * Author: Zhang Dongwei
 * Date: 2023/5/3 21:44
 * 逆波兰表达式求值
 */
public class zydl6_150 {

    public static void main(String[] args) {
//        String[] tokens = {"2","1","+","3","*"};
//        String[] tokens = {"4","13","5","/","+"};
        String[] tokens = {"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
        System.out.println(evalRPN(tokens));
    }

//    看的题解，自己没有做出来，主要是字符串转数字部分不知道怎么转
    public static int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++){
            if ("+".equals(tokens[i])){
                stack.push(stack.pop() + stack.pop());
            }else if ("-".equals(tokens[i])){
                stack.push(-stack.pop() + stack.pop());
            }else if ("*".equals(tokens[i])){
                stack.push(stack.pop() * stack.pop());
            }else if ("/".equals(tokens[i])){
                int temp1 = stack.pop();
                int temp2 = stack.pop();
                stack.push(temp2 / temp1);
            }else {
                stack.push(Integer.valueOf(tokens[i]));
            }
        }
        return stack.pop();
    }
}
